package com.healthcare;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;

/**
 * Servlet implementation class UserRegistration
 */
public class BookAppointment extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BookAppointment() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String inputDate = request.getParameter("time");
		String inputDoctor = request.getParameter("doctorid");
		String inputUser = request.getParameter("userid");

		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/aimsfirstconsultdb", "root",
					"");
			stmt = con.createStatement();

			String insertAppointmentSlotsSql = "insert into appointments (doctor_id, user_id, appointment_date) values ("
					+ inputDoctor + "," + inputUser + ",'" + inputDate + "')";
			stmt.executeUpdate(insertAppointmentSlotsSql);

			out.println("<p> Your Appointment is confirmed. Appointment details will be mailed to you. <br>Thank you for using our service.</p>");

			/* Send Email Confirmation to user */

			String getDocDetailsSql = "SELECT first_name,last_name, email, clinic_name, clinic_address, clinic_zip,"
					+ "phone, website from doctors where doctor_id="
					+ inputDoctor;

			rs = stmt.executeQuery(getDocDetailsSql);
			Doctor doctor = new Doctor();

			/* displaying doctor records */
			if (rs.next()) {
				String resfname = rs.getObject(1).toString();
				String reslname = rs.getObject(2).toString();
				String resmail = rs.getObject(3).toString();
				String resclinicname = rs.getObject(4).toString();
				String resclinicaddress = rs.getObject(5).toString();
				String rescliniczip = rs.getObject(6).toString();
				String resphone = rs.getObject(7).toString();
				String reswebsite = rs.getObject(8).toString();

				doctor.setFirstname(resfname);
				doctor.setLastname(reslname);
				doctor.setPhone(resphone);
				doctor.setEmail(resmail);
				doctor.setClinicname(resclinicname);
				doctor.setClinicaddress(resclinicaddress);
				doctor.setCliniczip(rescliniczip);
				doctor.setWebsite(reswebsite);
			}
			HttpSession session = request.getSession();
			String useremail = (String) session.getAttribute("email");
			String username = (String) session.getAttribute("username");
			SimpleDateFormat format = new SimpleDateFormat(
					"yyyy-MM-dd hh:mm:ss");
			Date appDate = format.parse(inputDate);
			sendConfirmationEmail(username, useremail, doctor, appDate);
		} catch (SQLException e) {
			throw new ServletException("Servlet Could not display records.", e);
		} catch (ClassNotFoundException e) {
			throw new ServletException("JDBC Driver not found.", e);
		} catch (ParseException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
					rs = null;
				}
				if (stmt != null) {
					stmt.close();
					stmt = null;
				}
				if (con != null) {
					con.close();
					con = null;
				}
			} catch (SQLException e) {
			}
			out.close();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	public void sendConfirmationEmail(String name, String useremail,
			Doctor doctor, Date appDate) {

		final String username = "firstconsultmail@gmail.com";
		final String password = "12-34-56";

		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.port", "587");

		Session session = Session.getInstance(props,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(username, password);
					}
				});

		try {
			SimpleDateFormat dateformat = new SimpleDateFormat("MM/dd/yyyy");
			SimpleDateFormat timeformat = new SimpleDateFormat("h:mm a");

			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("firstconsult@gmail.com"));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(useremail));
			message.setSubject("First Consult - Appointment Confirmation");
			String messageHtml = "<HTML> <P>" + "Dear " + name + ",<br/><br/>"
					+ "Your appointment is confirmed!!" + "<br /> <br />"
					+ "<b>Date of Appointment: </b>"
					+ dateformat.format(appDate) + " at "
					+ timeformat.format(appDate) + "<br /><br />"
					+ "<b>Physician Name: </b>" + doctor.getFirstname() + " "
					+ doctor.getLastname()
					+ " <br /><br /> <b>Address:</b> <br />"
					+ doctor.getClinicname() + " <br />"
					+ doctor.getClinicaddress() + "<br /> "
					+ doctor.getCliniczip()
					+ "<br /><br /><b>Physician Contact: </b>"
					+ doctor.getPhone()
					+ "<br /><br /><b>Physician Email: </b>"
					+ doctor.getEmail() + "</P></HTML>";

			message.setContent(messageHtml, "text/html; charset=utf-8");
			Transport.send(message);
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
}
